package com.fastadmin.service;

import com.fastadmin.common.FAConst;
import com.fastadmin.common.jedis.JedisTemplate;
import com.fastadmin.common.jwt.JwtTokenUtil;
import com.fastadmin.common.mapper.JsonMapper;
import com.fastadmin.mapper.impl.FUserMapper;
import com.fastadmin.pojo.FUser;
import com.google.common.collect.Maps;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.fastadmin.common.FAConst.FLoginConst.REDIS_USER_PREFIX;
import static java.util.Objects.isNull;

@Service
@Slf4j
@RequiredArgsConstructor
public class FUserService {
    private final FUserMapper fUserMapper;
    private final JedisTemplate jedisTemplate;
    public static final JsonMapper binder = new JsonMapper();



    /**
     * 根据token查询【user】
     *
     * @param token
     * @return
     */
    public FUser queryUserByToken(String token) {
        //解密token
        Long userId = JwtTokenUtil.getUserIdFromToken(token);
        if (Objects.isNull(userId)) {
            return null;
        }
        String key = REDIS_USER_PREFIX + userId;
        String userJson = jedisTemplate.get(key);
        if (StringUtils.isEmpty(userJson)) {
            // 登录超时
            return null;
        }
        //重设redis生存时间
        //jedisTemplate().pexpire(key, REDIS_TIME);
        FUser user = binder.fromJson(userJson, FUser.class);
        //判断是不是修改了密码了
        if (!JwtTokenUtil.validateToken(token, user)) {
            log.debug("userId:{}修改密码 token失效！", user.getId());
            return null;
        }
        return user;
    }

    /**
     * 登录逻辑
     *
     * @return
     */
    public Map<String, String> doLogin(FUser user) {
        HashMap<String, String> msg = Maps.newHashMap();
        //登录成功
        String token = new JwtTokenUtil().generateToken(user);
        jedisTemplate.Setex(FAConst.FLoginConst.REDIS_USER_PREFIX + user.getId(),
                binder.toJson(user), FAConst.FLoginConst.REDIS_USER_TIME);
        msg.put("token", token);
        msg.put("username", user.getUsername());
        msg.put("avatar", user.getAvatar());
        msg.put("userId", user.getId() + "");
        return msg;
    }


}
